package com.action;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.model.Customer;
import com.model.ItemTemp;
import com.model.Payment;
import com.model.Product;
import com.model.SaleOrder;
import com.model.SaleOrderItem;
import com.service.SaleService;
import com.service.impl.SaleServiceImpl;
import com.util.SerialNumberUtil;

@WebServlet("/SaleController")
public class SaleController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SaleOrder saleOrder = new SaleOrder();
	private List<ItemTemp> itemTempList = new ArrayList<ItemTemp>();

	public SaleController() {
		super();
		// TODO Auto-generated constructor stub
	}

	// 明细记录
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// TODO Auto-generated method stub

		HttpSession session = request.getSession();
		List<ItemTemp> itemList = (List<ItemTemp>) session
				.getAttribute("ItemTempList");
		SaleServiceImpl soid = new SaleServiceImpl();
		for (int i = 0; i < itemList.size(); i++) {
			ItemTemp itemTemp = itemList.get(i);
			SaleOrderItem saleOrderItem = new SaleOrderItem();
			Product product = soid.getProductDAO().getProduct(
					itemTemp.getProductNo());
			saleOrderItem.setSaleOrder_Id(saleOrder.getId());
			saleOrderItem.setProduct_Id(product.getId());
			saleOrderItem.setQuantity(itemTemp.getQuantity());
			saleOrderItem.setPrice(itemTemp.getSubtotal());

			System.out.println("<debug>" + saleOrderItem);

			soid.addOrderItem(saleOrderItem);
		}
		itemTempList.clear();
		session.setAttribute("ItemTempList", null);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		/*
		 * request.setCharacterEncoding("UTF-8");
		 * response.setCharacterEncoding("UTF-8");
		 * response.setContentType("text/html;charset=UTF-8");
		 */

		String method = request.getParameter("method");

		if ("addSaleOrder".equals(method))
			addSaleOrder(request, response);
		else if ("enterProduct".equals(method))
			enterProduct(request, response);
		else if ("removeProduct".equals(method))
			removeProduct(request, response);
		else if ("selectItemTemp".equals(method))
			selectItemTemp(request, response);
		else if ("selectSaleOrder".equals(method))
			selectSaleOrder(request, response);
		else {
			System.out.println("无请求！");
		}
	}

	// 结算
	protected void addSaleOrder(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String customerNo = request.getParameter("customerNo");
		String total = request.getParameter("total");
		String state = request.getParameter("state");
		String paymentMethod = request.getParameter("paymentMethod");

		SaleServiceImpl sod = new SaleServiceImpl();

		Customer customer = sod.getCustomerDAO().getCustomer(customerNo);
		int lastSaleId = sod.getLastNum();
		int saleNumber = lastSaleId + 1;
		String saleOrderNo = SerialNumberUtil.getSerialNumber("sale",
				saleNumber);

		saleOrder.setId(saleNumber);
		saleOrder.setSaleOrderNo(saleOrderNo);
		saleOrder.setCustomer_Id(customer.getId());
		saleOrder.setTotal(Double.parseDouble(total));
		saleOrder.setCreateDateTime(new Date());
		saleOrder.setState(Integer.parseInt(state));

		System.out.println("<debug>" + saleOrder);

		boolean b = sod.addOrder(saleOrder);// 保存订单

		Payment payment = new Payment();
		int paymentNumber = sod.getPaymentNum() + 1;
		String paymentNo = SerialNumberUtil.getSerialNumber("pay",
				paymentNumber);

		payment.setPaymentNo(paymentNo);
		payment.setPaymentMethod(Integer.parseInt(paymentMethod));
		payment.setAmount(Double.parseDouble(total));
		payment.setSaleOrder_Id(saleOrder.getId());

		System.out.println("<debug>" + payment);

		boolean bb = sod.addPayment(payment);// 保存支付信息
		String resultJson = null;

		if (b & bb) {
			resultJson = "{\"success\":true,\"msg\":\"销售完成！\"}";
		} else {
			resultJson = "{\"success\":false,\"msg\":\"销售失败!\"}";
		}
		response.getWriter().print(resultJson);
		response.getWriter().flush();
	}

	// 录入图书
	protected void enterProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SaleServiceImpl aod = new SaleServiceImpl();

		String productNo = request.getParameter("productNo");
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		double discount = Double.parseDouble(request.getParameter("discount"));

		DecimalFormat df = new DecimalFormat(".##");
		Product product = aod.getProductDAO().getProduct(productNo);
		double subtotal = product.getPrice() * quantity * discount;
		subtotal = Double.parseDouble(df.format(subtotal));
		ItemTemp itemTemp = new ItemTemp();
		List list = (List) request.getSession().getAttribute("ItemTempList");
		int id = 0;
		if (list == null || list.size() == 0) {
			id = 1;
		} else {
			id = list.size() + 1;
		}
		itemTemp.setId(id);
		itemTemp.setProductNo(product.getProductNo());
		itemTemp.setProductName(product.getProductName());
		itemTemp.setPrice(product.getPrice());
		itemTemp.setDiscount(discount);
		itemTemp.setSubtotal(subtotal);
		itemTemp.setQuantity(quantity);
		itemTempList.add(itemTemp);
		// discount);
		System.out.println("<debug>" + itemTempList);
		request.getSession().setAttribute("ItemTempList", itemTempList);

	}

	// 移除不购买的图书
	protected void removeProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int id = Integer.parseInt(request.getParameter("id"));
		HttpSession session = request.getSession();
		List<ItemTemp> list = (List<ItemTemp>) session
				.getAttribute("ItemTempList");
		list.remove(id - 1);
		for (ItemTemp it : list) {
			if (id < it.getId()) {
				it.setId(it.getId() - 1);
			}
		}
		session.setAttribute("ItemTempList", list);
	}

	// 显示录入的图书
	protected void selectItemTemp(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		if (session == null || session.getAttribute("ItemTempList") == null) {
			response.getWriter().print(
					"{\"success\":false,\"msg\":\"没有购买的BOOK，请购买！\"}");
			return;
		}
		List<ItemTemp> itemTempList = (List<ItemTemp>) session
				.getAttribute("ItemTempList");
		int total = itemTempList.size();
		// json格式化
		Map<String, Object> map = new HashMap<String, Object>();
		map = new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", itemTempList);
		String itemTempJson = JSON.toJSONString(map);

		response.getWriter().print(itemTempJson);
		response.getWriter().flush();
	}

	// 查询订单记录
	protected void selectSaleOrder(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		String key = request.getParameter("key");
		String type = request.getParameter("type");
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		int startPage = Integer.parseInt(page);
		int endRows = Integer.parseInt(rows);
		SaleService sod = new SaleServiceImpl();
		response.getWriter()
				.print(sod.selectSaleOrder(key, type, startPage, endRows, sort,
						order));
		response.getWriter().flush();
	}
}
